import React, { FC } from "react";
import { Link, useLocation } from "react-router-dom";
import { routes } from "@/components/App/routes";
import { observer } from "mobx-react-lite";
import cls from "@/styles/feature/Sidebar.module.scss";
import cn from "classnames";
import { Icon } from "@/ui/Icons/Icon";
import logo from "@/assets/images/logo.png";
import { useToken, useUserMe } from "@/store/auth";

export const Sidebar: FC = observer(() => {
  const { pathname } = useLocation();
  const { logout } = useToken();
  const { userMe } = useUserMe();

  return (
    <div className={cls.root}>
      <div className={cls.logo_wrapper}>
        <div className={cls.logo}>
          <img src={logo} alt="logo" />
        </div>
      </div>

      <div className="divider" />
      <div className={cls.links}>
        {!!userMe &&
          routes
            .filter((r) => {
              let hasPermission = false;
              r.permissions.map((p) => {
                if (userMe.groups.includes(p)) hasPermission = true;
              });
              return hasPermission || userMe.is_superuser;
            })
            .map((route) => {
              return (
                <Link
                  to={route.path}
                  key={route.path}
                  className={cn(cls.link, {
                    [cls.active]:
                      route.path === pathname ||
                      (route.path !== "/" && pathname.includes(route.path)),
                    [cls.fillIcon]: route.fillIcon,
                  })}
                >
                  <Icon name={route.icon} /> {route.name}
                </Link>
              );
            })}
      </div>
      <div className={cls.space} />
      <div className={cls.logout}>
        <button type="button" className={cls.link} onClick={logout}>
          <Icon name="exit" /> Выход
        </button>
      </div>
    </div>
  );
});
